package com.javaweb.admin.config;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javaweb.admin.entity.NcTaskLog;
import com.javaweb.admin.entity.Scheduled;
import com.javaweb.admin.entity.SysMsfxYjbg;
import com.javaweb.admin.entity.VSyOnhand;
import com.javaweb.admin.entity.querysealdrugreport.Alibaba_alihealth_synergy_yzw_querysealdrugreport_response;
import com.javaweb.admin.entity.querysealdrugreport.Ocr_seal_drug_report_d_t_o;
import com.javaweb.admin.mapper.ScheduledMapper;
import com.javaweb.admin.mapper.SysMsfxYjbgMapper;
import com.javaweb.admin.mapper.VSyOnhandMapper;
import com.javaweb.admin.query.SySyxxQuery;
import com.javaweb.admin.service.AbstractJob;
import com.javaweb.admin.service.INcTaskLogService;
import com.javaweb.admin.service.ISySyxxService;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.FileUtils;
import com.javaweb.common.utils.JsonResult;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAlihealthSynergyYzwQuerysealdrugreportRequest;
import com.taobao.api.response.AlibabaAlihealthSynergyYzwQuerysealdrugreportResponse;
import org.aspectj.bridge.ICommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class GetYJBGJob extends AbstractJob {
    @Autowired
    ScheduledMapper scheduledMapper;

    @Autowired
    INcTaskLogService iNcTaskLogService;

    @Autowired
    SysMsfxYjbgMapper sysMsfxYjbgMapper;

    @Override
    public String getName() {
        QueryWrapper<Scheduled> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classpath",this.getClass().getName());
        Scheduled entity = scheduledMapper.selectOne(queryWrapper);
        return entity.getName();
    }

    private Integer saveYJBG(String result) {
        JSONObject obj = JSONObject.parseObject(result);
        Alibaba_alihealth_synergy_yzw_querysealdrugreport_response response = JSONObject.parseObject(obj.getString("alibaba_alihealth_synergy_yzw_querysealdrugreport_response"), Alibaba_alihealth_synergy_yzw_querysealdrugreport_response.class);
        SysMsfxYjbg entity = new SysMsfxYjbg();
        Integer totolNum = 0;
        Map<String, Object> param = new HashMap<>();
        if (response.getResult().getResponse_success()) {
            if(response.getResult().getModel().getTotal_num()>0) {
                totolNum = response.getResult().getModel().getTotal_num();
                for (Ocr_seal_drug_report_d_t_o dto : response.getResult().getModel().getResult_list().getOcr_seal_drug_report_d_t_o()) {
                    entity.setBatchNo(dto.getBatch_no());
                    entity.setCreateTime(DateUtils.now());
                    entity.setDrugEntBaseInfoId(dto.getDrug_ent_base_info_id());
                    entity.setDrugName(dto.getDrug_name());
                    entity.setDrugReportV2Id(dto.getDrug_report_v2_id());
                    entity.setSealedReportUrl(dto.getSealed_report_url());
                    entity.setPkgSpec(dto.getPkg_spec());
                    entity.setPrepnSpec(dto.getPrepn_spec());
                    entity.setProdCode(dto.getProd_code());
                    entity.setReportDate(dto.getReport_date());
                    entity.setFilePath("");
                    param.clear();
                    param.put("batch_no", dto.getBatch_no());
                    param.put("prod_code", dto.getProd_code());
                    if (sysMsfxYjbgMapper.selectByMap(param).size() == 0) {
                        sysMsfxYjbgMapper.insert(entity);
                    }
                }
            }else{
                logger.info("药检报告查询返回："+result);
            }
        } else{
        logger.info("药检报告查询失败："+result);
    }
    return totolNum;

}

    @Override
    public void execute() {
        NcTaskLog taskLog = new NcTaskLog();
        taskLog.setTaskType("查询药检报告");
        taskLog.setBillCount(0);
        taskLog.setStartTime(DateUtils.now());
        String material_code = "";
        String batch_code="";
        try {
            TaobaoClient client = new DefaultTaobaoClient(CommonConfig.taobaoURL, CommonConfig.taobaoAppKey, CommonConfig.taobaoAppSecret);
            AlibabaAlihealthSynergyYzwQuerysealdrugreportRequest req = new AlibabaAlihealthSynergyYzwQuerysealdrugreportRequest();
            req.setRefEntId("58d60ce90afa4d359e0ee9ea4384f185");
            req.setBeginTime(DateUtils.getDate()+ " 00:00:00");
            req.setEndTime(DateUtils.getTime());
            req.setPage(1L);
            req.setPageSize(20L);
            AlibabaAlihealthSynergyYzwQuerysealdrugreportResponse rsp = client.execute(req);
            String result = rsp.getBody();
            Integer totalNum= saveYJBG(result);
            double totalPage = totalNum*1.0/req.getPageSize();
            Long pageCount =  Math.round(Math.ceil(totalPage));
            if(pageCount>1)
            {
                for (Integer i = 2; i <= pageCount; i++) {
                    req.setPage(i.longValue());
                    rsp = client.execute(req);
                    saveYJBG(rsp.getBody());
                }
            }
            taskLog.setBillNo("");
            taskLog.setEndTime(DateUtils.now());
            iNcTaskLogService.save(taskLog);
        }
        catch(Exception ex)
        {
            logger.info("药检报告查询失败："+ex.getMessage());
        }

    }
}

